package com.abc.recycling.controller;

import com.abc.recycling.model.User;
import com.abc.recycling.model.Order;
import com.abc.recycling.service.UserService;
import com.abc.recycling.service.CollectorOrderService;
import com.abc.recycling.service.EvaluationService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.ArrayList;

@Slf4j
@Controller
@RequestMapping("/collector")
@RequiredArgsConstructor
public class CollectorController {

    private final UserService userService;
    private final CollectorOrderService collectorOrderService;
    private final EvaluationService evaluationService;

    @GetMapping({"", "/", "/index"})
    public String index(Authentication authentication, Model model) {
        try {
            log.info("访问回收员首页");
            if (authentication == null) {
                log.error("用户未认证");
                return "redirect:/login";
            }
            
            User collector = userService.getUserByUsername(authentication.getName());
            if (collector == null) {
                log.error("未找到用户信息: {}", authentication.getName());
                return "redirect:/login";
            }
            
            log.debug("当前登录用户: {}", collector.getUsername());
            model.addAttribute("collector", collector);
            
            return "collector/index";
        } catch (Exception e) {
            log.error("访问首页出错: ", e);
            throw e;
        }
    }

    @GetMapping("/dashboard")
    public String dashboard(Authentication authentication, Model model) {
        log.info("开始加载回收员仪表盘数据");
        
        // 获取当前登录的回收员信息
        User collector = userService.getUserByUsername(authentication.getName());
        log.debug("当前回收员ID: {}", collector.getId());
        
        // 获取今日订单数
        long todayOrders = collectorOrderService.countOrdersByCollectorAndDate(collector.getId(), LocalDateTime.now());
        model.addAttribute("todayOrders", todayOrders);
        log.debug("今日订单数: {}", todayOrders);
        
        // 获取待处理订单数
        long pendingOrderCount = collectorOrderService.countOrdersByStatus("PENDING");
        model.addAttribute("pendingOrderCount", pendingOrderCount);
        log.debug("待处理订单数: {}", pendingOrderCount);
        
        // 获取进行中订单数
        long processingOrderCount = collectorOrderService.countOrdersByCollectorAndStatus(collector.getId(), "PROCESSING");
        model.addAttribute("processingOrderCount", processingOrderCount);
        log.debug("进行中订单数: {}", processingOrderCount);
        
        // 获取评分统计
        Double averageRating = evaluationService.getCollectorAverageRating(collector.getId());
        model.addAttribute("averageRating", averageRating != null ? averageRating : 0.0);
        log.debug("平均评分: {}", averageRating);
        
        // 获取评分分布
        List<Integer> ratingDistribution = evaluationService.getCollectorRatingDistribution(collector.getId());
        model.addAttribute("ratingDistribution", ratingDistribution);
        log.debug("评分分布: {}", ratingDistribution);
        
        // 获取订单趋势数据
        List<Map<String, Object>> orderTrend = collectorOrderService.getOrderTrendByCollector(collector.getId());
        
        // 验证订单趋势数据
        if (orderTrend == null || orderTrend.isEmpty()) {
            log.warn("订单趋势数据为空");
            orderTrend = new ArrayList<>();
        }
        
        // 确保每个数据项都有正确的格式
        for (Map<String, Object> data : orderTrend) {
            if (!data.containsKey("date") || !data.containsKey("count")) {
                log.error("订单趋势数据格式错误: {}", data);
            }
            // 确保count是数字类型
            if (data.get("count") instanceof String) {
                data.put("count", Long.parseLong((String) data.get("count")));
            }
        }
        
        model.addAttribute("orderTrend", orderTrend);
        log.debug("订单趋势数据: {}", orderTrend);
        
        log.info("回收员仪表盘数据加载完成");
        return "collector/dashboard";
    }
} 